package cn.szzsi._webpc;


import cn.szzsi._web.BaseWebController;
import cn.szzsi.common.bean.dto.Msg;
import cn.szzsi.common.kit.BackUtil;
import cn.szzsi.common.kit.SessionUtil;
import cn.szzsi.common.model.Member;
import cn.szzsi.common.model.Tocash;
import cn.szzsi.common.model.TocashBank;
import cn.szzsi.service.UserBalanceService;
import cn.szzsi.service.UserService;
import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.ehcache.CacheKit;
import com.jfinal.weixin.sdk.api.ApiConfigKit;

import java.math.BigDecimal;
import java.util.List;

/**
 * 提现
 * Created by yuanzheng on 2016/11/25.
 */
public class CashingController extends BaseWebPcController<Tocash>{
    private String shopId;//用户的shopId就是商户的id
    private String path;//模板路径

    //会员提现记录
    public void list(){
        shopId= getPara("shopId");
        Member member=getLoginMember();
        List<Tocash> toCashingList= Tocash.getByMemberId(member.getStr("id"));
        setAttr("toCashingList",toCashingList);
        getTemplatePath(shopId,"tocashing_list");

    }

    /**
     * 买家发起提现申请,还有当上一笔订单申请通过,该笔订单才能发起申请
     */
    public void save(){
        Member member=getLoginMember();
        String bankId=getPara("bankId");//银行卡id
        String bankType=getPara("bankType");
        String cashAmount=getPara("cashAmount");//提现金额
        String phonecode=getPara("phonecode");
        if(CacheKit.get("sms",member.getPhone())==null){
            renderJson(Ret.fail("info","手机验证码已过期,请重新获取!"));
            return;
        }
        if(!phonecode.equals(CacheKit.get("sms",member.getPhone()).toString())){
            renderJson(Ret.fail("info","手机验证码错误!"));
            return;
        }
        Tocash toCashing= Tocash.getLastByMemberId(member.getId());//上一笔订单
        if(toCashing!=null && toCashing.getStatus()== Tocash.ToCashingStatus.inToCashing.ordinal()){//最后一笔订单在提现中
            renderJson(BackUtil.fail("亲,您有一笔提现还未审核通过哦!"));
            return;
        }
        TocashBank tocashBank=TocashBank.getByMemberId(member.getId());
        if(tocashBank==null){
            renderJson(BackUtil.fail("亲,您还没有绑定提现银行卡哦!"));
            return;
        }
        if((!"0".equals(bankType) && StrKit.isBlank(tocashBank.getAliPayAccount()))|| (!"0".equals(bankType) && StrKit.isBlank(tocashBank.getWeChatAccount()))){//支付宝
            renderJson(BackUtil.fail("亲,该种提现方式没有绑定账号,请先绑定或者换种提现方式!"));
            return;
        }

        BigDecimal deposit=UserBalanceService.service.getAvailBalance(member);//可提余额
        BigDecimal bdCashAmount=new BigDecimal(cashAmount);
        if(bdCashAmount.compareTo(deposit)>0){
            renderJson(BackUtil.fail("亲,您的账户余额为"+deposit.toString()+"元,最多只能提取"+deposit.toString()+"元哦!"));
            return;
        }
        String member_id=member.getStr("id");
        Tocash.saveToCashing(member_id,"-1",bankId,bankType,cashAmount);
        renderJson(BackUtil.success());


    }



}
